SHELL := /bin/bash

# For wich architecture is this kernel made for?
ARCH := x86

CC := gcc
CXX := g++
LD := ld
AR := ar
AS := nasm
CFLAGS := -DARCH=$(ARCH) -fno-builtin -nostdinc -Isrc/include -Isrc/include/clib -pipe -O2 -Wall -Werror -c
CXXFLAGS := -fno-rtti -fno-exceptions -fno-stack-protector
LDFLAGS := -Tsrc/arch/$(ARCH)/linker.lds -Map kernel.map
ASFLAGS := -felf32

VERSION := 0.01
KERNEL := koron-$(VERSION)
LIBC := libc.a

include src/makefile.objs

all:	src/include/arch $(KERNEL)

$(KERNEL):	$(LIBC) $(KOBJS)
	@echo -e "\e[34mLD\t\e[31m\e[1m$@\e[0m"
	@$(LD) $(LDFLAGS) $(KOBJS) $(LIBC) -o $@

$(LIBC):	$(LIBOBJS)
	@echo -e "\e[34mAR\t\e[31m\e[1m$@\e[0m"
	@ar -rv $@ $(LIBOBJS) &> /dev/null

clean:
	@for file in $(KOBJS) $(LIBOBJS) kernel.map $(KERNEL) $(LIBC) iso koron.iso; do \
			echo -e "\e[31m\e[1mRM\t\e[34m$$file\e[0m"; \
			rm -fr $$file 2&> /dev/null || true; \
	done;

.cpp.o:
	@echo -e "\e[30m\e[1mCXX\t\e[22m\e[34m$@\e[0m"
	@$(CXX) $(CFLAGS) $(CXXFLAGS) -o $@ $<
.S.o:
	@echo -e "\e[30m\e[1mAS\t\e[22m\e[34m$@\e[0m"
	@$(AS) $(ASFLAGS) -o $@ $<

# The kernel is made in c++. However if we have a piece of C code...
.c.o:
	@echo -e "\e[30m\e[1mCC\t\e[22m\e[34m$@\e[0m"
	@$(CC) $(CFLAGS) -c -o $@ $<

src/include/arch:
	ln -s arch-$(ARCH) src/include/arch

# This creates a bootable ISO with grub and the kernel
iso:	all
	@mkdir -p iso/boot/grub
	@cp $(KERNEL) iso/boot/
	@cp menu.lst.template iso/boot/grub/menu.lst
	@sed -i 's/(KNAME)/'$(KERNEL)'/' iso/boot/grub/menu.lst

	@cp /usr/lib/grub/i386-pc/stage2_eltorito iso/boot/grub/
	@mkisofs -U -b boot/grub/stage2_eltorito -no-emul-boot \
		-f -hide boot.catalog -boot-load-size 4 -boot-info-table \
		-o "koron.iso" -V "Koron LiveCD" -iso-level 3 \
		-quiet iso/ &> /dev/null
